将一个返回foo的promise映射到另一个返回bar的promise?

时间:2019-04-28 14:43:53

标签: javascript vue.js axios es6-promise

我有一个函数,该函数生成XMLHttpRequest并返回请求和请求的响应。

但是我想返回一个仅包含响应中一个字符串的Promise。

例如,我只想返回response = {status, data}

,而不是将承诺分解为response.data.some_field等。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

如果在promise上调用.then,则会产生另一个promise,该promise将解析为您在回调函数中返回的内容。因此,请遵循您正在创建的当前承诺,然后添加以下内容:

.then((response) => {
  return response.data.some_field;
});

因此完整功能可能看起来像这样:

function getStuff() {
   return new Promise((resolve, reject) => {
     //somethingWithXMLHttpRequest      
   }).then((response) => {
      return response.data.some_field;
   });
}

答案 1 :(得分:1)

您要寻找的是promise chaining。链接转到有关Promise链接的mozilla的文档页面。

function httpRequestAsync () {
    // Return a promise... This is where your XMLHttpRequest takes place
}

function getStuffAsync() {

   // Make your http request, chain the return promise, 
   // and return a promise, which resolves to the chosen field.
   return httpRequestAsync() //Calling .then() on this promise is promise chaining.
       .then((response) => { 
          return response.data.some_field;
       });
}

function someBusinessLogicFunction () {

     let yourString = "";

     getStuffAsync()
         .then((response) => {
              yourString = response; // yourString does in fact equal the response param... :).catch(() => {
               console.log("Something went wrong, or this answer sucks ha ha!");
          }); 
     }) 
}


// Or using async/await, for fun

async someBusinessLogicFunction2 () {

     let yourString = "";

     try {
         yourString = await getStuffAsync();
     } catch (e) {
         console.log("Something went wrong, or this answer sucks ha ha!");
     }
}

我的示例将HTTP请求拆分为一个函数,并声明了另一个函数,该函数调用该函数并执行promise链接。您可以省略第二个函数,然后从执行HTTP请求的函数返回链接的诺言。

答案 2 :(得分:0)

您有类似的内容(在编辑问题之前从代码块中获取了它)

 const promise = axios
    .post(url("fistbump"), data)
    .then(result => {
      window.console.log("Got fistbump response: ", result.data);
      localStorage.setItem(ACCOUNT_TOKEN_FIELD, result.data.key);
    });

  return promise;

如果Axios承诺遵守ES6承诺规范,则可以简单地从.then子句中返回所需内容,以将价值包装在承诺中,从而为您提供

 const promise = axios
    .post(url("fistbump"), data)
    .then(result => {
      window.console.log("Got fistbump response: ", result.data);
      localStorage.setItem(ACCOUNT_TOKEN_FIELD, result.data.key);
      return result.data;
    });

  return promise;