简体   繁体   中英

Promise.finally not returning as the last call of the chain

I have the following chain of promise, which I expected the resolve function of .finally() to be promise to be returned, but instead the last .then() is the one that gets returned.

exportReportToJson (url,opts) {
    const requestJSON = {
      "values" : []
    };

    return this.getValue(url)
    .then( value => {
      requestJSON.values.push(value);
      if(opts.extraValue){
        return this.getExtraValue(value);
      }else{
        return Promise.finally();
      }
    })
    //The index of .push gets returned instead
    .then(extraValue => requestJSON.values.push(extraValue))
    //But I want requestJSON to always be the returned Promise
    .finally( () => requestJSON)
}

As you can see I want finally to always be the final promise to be returned, is that not what is for? What am I missing here? I thought it worked as an .always()

No await please.

I want to have a conditional .then while not changing the final .then basically.

.finally does not let you change what the promise resolves as; it's just meant for doing teardown logic. If the promise resolved with some value, it remains resolved with that value; if it rejected with some value, it remains rejected with that value.

You can see more about its behavior here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

If you need to change the value, then use .then or .catch. If you also want identical logic in both, then you'll need to use both. This either means duplicating the code, or extracting it to a named function.

There is no Promise.finally function. It seems like what you actually wanted is

function exportReportToJson (url,opts) {
  return this.getValue(url).then(value => {
    if (opts.extraValue) {
      return this.getExtraValue(value).then(extraValue => [value, extraValue]);
    } else{
      return [value];
    }
  }).then(values => {
    const requestJSON = {values};
    return requestJSON;
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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