我有三个函数,它们都需要特定的时间来执行,然后当它们全部完成时,我需要触发一个特定的函数。使用下面的代码,我能够通过一个函数获得预期的结果,但是对于多个函数,我没有做到这一点,请帮助我编辑这段代码,等待我的3函数,然后控制台它们返回的数据。
var promise = new Promise(function(resolve, reject)
{
setTimeout(function()
{
resolve('hello world');
}, 2000);
});
promise.then(function(data)
{
console.log(data);
});发布于 2020-01-22 13:02:55
Promise.all()将接受一组承诺作为参数,并等待所有承诺完成。
var promise1 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('function 1 resolved');
}, Math.random() * 10000);
});
var promise2 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('function 2 resolved');
}, Math.random() * 10000);
});
var promise3 = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('function 3 resolved');
}, Math.random() * 10000);
});
Promise.all([promise1, promise2, promise3])
.then(resArr => {
console.log(resArr)
})通过使用附加到.catch()的promise.all(),可以捕获在任何承诺中发生的错误。
Promise.all([promise1, promise2, promise3])
.then(resArr => {
console.log(resArr)
})
.catch(error => console.log(error))发布于 2020-01-22 12:34:49
Javascript有一个内置的方法,它等待您承诺要解决的所有问题。
Promise.all([promise1, promise2, promise3]).then(function(values) {
console.log(values);
});所以对于你的案子:
const promiseFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
};
const promise1 = promiseFunction();
const promise2 = promiseFunction();
const promise3 = promiseFunction();
Promise.all([promise1, promise2, promise3])
.then((result) => {
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);
})结果是从每个承诺返回的值数组。
发布于 2020-01-22 12:28:05
您可以引用此代码,其中函数被调用3次,有两种方法可以这样做,您还可以看到不同的行为。
// Function which returns a promise and resolves in 2 seconds
const promiseFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
};
// Asynchronous function 1
const asyncFunction1 = async() => {
console.log(await promiseFunction());
console.log(await promiseFunction());
console.log(await promiseFunction());
}
// Asynchronous function 2
const asyncFunction2 = async() => {
let a = promiseFunction();
let b = promiseFunction();
let c = promiseFunction();
console.log(await a);
console.log(await b);
console.log(await c);
} 看到之间的区别
asyncFunction1()和asyncFunction2()调用
使用异步/等待是一种ES6方式,您也可以进行.then()链接
promiseFunction().then(() => {
//function body here
})https://stackoverflow.com/questions/59859756
复制相似问题