简体   繁体   English

javascript promise 链取不按顺序

[英]javascript promise chain with fetch not in sequence

I want to dynamically build a promise chain, that should do things in the background.我想动态构建一个 promise 链,它应该在后台执行操作。 Mainly it should do some output on the web page.主要是它应该在 web 页面上做一些 output。

That works until I put promises from fetch into the chain.这一直有效,直到我将fetch的承诺放入链中。 Those promises are not executed in the expected sequence.这些承诺未按预期顺序执行。

The following example shows how the chain is build:以下示例显示链是如何构建的:

var chain = Promise.resolve();
for(var i = 0; i < actions.length; ++i)
  chain = actions[i].extendChain(chain);

function actionExample(chain) {
  return chain.then(...);
}

That works with direct output:这适用于直接 output:

function actionOutput(chain) {
  return chain.then(new Promise(resolve => {
    print('text');
    resolve();
  }));
}

But fetch or is not in sequence:但是 fetch or 不按顺序:

function actionLoad(chain) {
  const url = '...';
  return chain.then(new Promise(() => print('run action load\n')))
    .then(() => fetch(url))
    .then((response) => response.json())
    .then(processResponse)
    .then(requestOutput)
    .then(receiveOutput);
}

The function requestOutput also contains a fetch, but already the call of processResponse is delayed. function requestOutput也包含一个 fetch,但是processResponse的调用已经被延迟了。

What can I change so that all steps are executed in the wanted sequence?我可以更改什么以便所有步骤都按所需顺序执行?

There's absolutely no reason to create new promises here.绝对没有理由在这里创建新的承诺。 Passing a Promise instance to .then() is also incorrect as it requires one or two functions.Promise实例传递给 .then .then()也是不正确的,因为它需要一个或两个函数。

The .then() method always returns a new promise that resolves with the return value of the function provided .then .then()方法总是返回一个新的 promise,它解析为提供的 function 的返回值

function actionOutput(chain) {
  return chain.then(() => print('text'));
}


function actionLoad(chain) {
  const url = '...';
  return chain
    .then(() => print('run action load\n')) // resolves with return value of
                                            // `print()`, probably `undefined`
    .then(() => fetch(url))
    .then((response) => response.ok ? response.json() : Promise.reject(res))
    .then(processResponse)
    .then(requestOutput)
    .then(receiveOutput);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM