这似乎是一个愚蠢的问题,但我是这个话题的新手。在下面的脚本中,我有两个承诺。到现在为止"第二个承诺"首先执行,然后执行"firstpromise"。因为在"第二次承诺"中我设定的时间更少。但是如何执行"firstpromise"呢?首先,在完成之后,开始执行"第二个承诺"?如何重写
下面的脚本(async function()
{
//var final = new Array();
var final;
const firstPromise = new Promise(
function(resolve)
{
let result = 2 + 2;
resolve(result);
setTimeout(() => console.log("please show me first"), 2000);
});
const secondPromise = new Promise(
function(resolve)
{
let result2 = 0;
resolve(result2 + 1);
setTimeout(() => console.log("please show me second"), 1000);
});
var myP = Promise.all([firstPromise, secondPromise]).then((values) => {
return values[0]+values[1];
});
return myP;
})();
(async function()
{
//var final = new Array();
var final;
const firstPromise = new Promise(
function(resolve)
{
let result = 2 + 2;
resolve(result);
setTimeout(() => console.log("please show me first"), 2000);
});
const secondPromise = new Promise(
function(resolve)
{
let result2 = 0;
resolve(result2 + 1);
setTimeout(() => console.log("please show me second"), 1000);
});
var myP = Promise.all([firstPromise, secondPromise]).then((values) => {
return values[0]+values[1];
});
return myP;
})();
Quentin的回答是正确的:您传递给new Promise
的功能立即发生。然而,因为你已经在async
函数中有了这个,你可以在它里面await
Promises。这将暂停async
函数,直到承诺解决,所以不像你的Promise.all
函数,等待你显式的new Promise
并行承诺,我的函数等待那些承诺串行。
此外,如果您希望编写的new Promise
结构等待setTimeout
中的操作,则需要在setTimeout
调用的回调中等待并调用resolve
方法,而不是像您所拥有的那样在它们之外。
console.log("start");
(async function () {
const firstValue = await new Promise(
// ^^^^^
function (resolve) {
let result = 2 + 2;
setTimeout(() => {
console.log("please show me first");
resolve(result); // Promise resolves after 2000ms
}, 2000);
});
const secondValue = await new Promise(
// ^^^^^
function (resolve) {
let result2 = 0;
setTimeout(() => {
console.log("please show me second");
resolve(result2 + 1);
}, 1000);
});
// These are values, not promises, because you await them.
// However, the async function still returns a Promise, because
// "async" covers the asynchronicity of the Promises you await.
return firstValue + secondValue;
})().then(x => console.log(x)); // or .then(console.log)
你不能执行承诺。
你可以执行一个函数
如果你把一个函数传递给一个Promise构造函数,那么它将被(由Promise构造函数)立即执行。
没有办法延迟传递给Promise构造函数的函数的执行。
你可以把对new Promise
的调用封装在函数中,然后只在第一个promise被解析时调用第二个函数。
(但是请注意,在您的示例中,对setTimeout
的调用发生在调用resolve
函数之后的)。