我在尝试第一次拒绝时使用的诺言出现类型错误,但据我所知,它看起来像我找到的示例。我究竟做错了什么?



var resolve, reject;
exports.handler = (event, context, callback) =>
{

	//var filePromise = new Promise(ProcessFile(resolve, reject));



	var filePromise = new Promise(function ProcessFile()
	{
		console.log("Processing file");
		return new Promise((resolve, reject) => {
		var array;

		if(array.length <0)
		{
			resolve("We have stuff in the array, looks promising");
		}
		else
		{
			reject("Something went wrong populating the array");
		}

		});
	});

	filePromise.then(CheckHeaders());

	function CheckHeaders()
	{
		return new Promise((resolve, reject) =>
		{
			console.log("Checking headers");

			reject("Unauthorised");
		});	//close promise
	 }	//close function
};

最佳答案

您只需要一个承诺。



var filePromise = new Promise(function(resolve, reject) {
  console.log("Processing file");
  var array = [1];

  if (array.length > 0) {
    resolve("We have stuff in the array, looks promising");
  } else {
    reject("Something went wrong populating the array");
  }
});

function CheckHeaders() {
  return new Promise((resolve, reject) => {
    console.log("Checking headers");

    reject("Unauthorised");
  }); //close promise
}

filePromise
  .then(res => {
    console.log(res)
    CheckHeaders()
      .then(res2 => console.log(res2))
  }).catch(err => console.warn(err));





正如@Bergi指出的那样,最好只做出一个整体承诺。



var filePromise = new Promise(function(resolve, reject) {
  console.log("Processing file");
  var array = [1];

  if (array.length > 0) {
    resolve("We have stuff in the array, looks promising");
  } else {
    reject("Something went wrong populating the array");
  }

  //here check headers
  reject("Unauthorised");


});

filePromise
  .then(res => {
    console.log(res)
  }).catch(err => console.warn(err));

07-24 09:39