gpt4 book ai didi

JavaScript 减少 Promise 不按顺序返回

转载 作者:行者123 更新时间:2023-12-03 03:16:25 26 4
gpt4 key购买 nike

由于某种原因,所有函数同时返回。

我想等待第一个函数解析,然后在调用第二个函数之前调用_done(),然后调用_done(),然后调用第三个函数并然后再次调用_done()

每次调用 _done() 时,我都想传递从上一个函数调用中解析出来的值。

工作演示在这里 https://repl.it/MeHl/9

"use-strict"

function _test(actions){
return actions.reduce((chain, action) => {
const func = this[action.functionToCall](action.argumentToSend);
return chain.then(() => func()).then(val => console.log(val));
}, Promise.resolve().then(val => _done()));
}

function _one(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve();
}, 2000);
})
}

function _two(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve();
}, 2000);
})
}

function _three(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve();
}, 2000);
})
}

function _done(data){
console.log(data);
}

const arrayOfObjects = [
{ functionToCall: '_one', argumentToSend: 'Yay function one was called with this argument' },
{ functionToCall: '_two', argumentToSend: 'Yay function two was called with this argument' },
{ functionToCall: '_three', argumentToSend: 'Yay function three was called with this argument' },
];

_test(arrayOfObjects);

所以日志应该看起来像

Yay function one was called with this argument
resolvedFromOne
Yay function two was called with this argument
resolvedFromTwo
Yay function three was called with this argument
resolvedFromThree

最佳答案

此代码产生预期的输出

    function _test(actions){
return actions.reduce((chain, action) => {
return chain.then(() => action.functionToCall(action.argumentToSend)).then(val => console.log(val));
}, Promise.resolve());
}

function _one(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve('resolvedFromOne');
}, 2000);
})
}

function _two(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve('resolvedFromTwo');
}, 2000);
})
}

function _three(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve('resolvedFromThree');
}, 2000);
})
}

// not required
function _done(data){
console.log(data);
}

const arrayOfObjects = [
{ functionToCall: _one, argumentToSend: 'Yay function one was called with this argument' },
{ functionToCall: _two, argumentToSend: 'Yay function two was called with this argument' },
{ functionToCall: _three, argumentToSend: 'Yay function three was called with this argument' },
];

_test(arrayOfObjects);

关于JavaScript 减少 Promise 不按顺序返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46753142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com