首页 > 解决方案 > 如何链接我的承诺 - 获取不返回所需的结果

问题描述

Fetch Promise 对我不起作用

在使用 Javascript Promises 方面,我是一个新手。在我目前的项目中,我相信 Promises 是我想要完成的任务的候选者。该项目很简单,它是向客户提交报价(或估算)的在线表格。

我正在处理将显示已提交报价的页面 - ( view-quote.html )

这是分解的任务:

同步还是异步?

由于一个查询依赖于另一个查询,我想我可以使用 Fetch 语句,它是“then-able”。

我想我应该使用异步代码来完成这个任务,对吧?不过我不确定。也许我需要传统的“回调”?

我当前的非工作代码...

这是我所得到的。我按照我在 Stack 网站上找到的提示和教程拼凑起来。

var getQuote = function() {
   fetch(apiQuoteUrl+"GL555")  // for testing, I hardcoded a quote num
  .then(status)
  .then(json)
  .then(function(data) {
    // WORKS - this DOES return me the client id
    //alert(data[0].client_id);
    gClient_id = data[0].client_id; // move to global var
  }).catch(function(error) {
    console.log('Request failed', error);
  });
};


// This function takes one parameter, the client id
// which comes from the fetch call above.
var getClient = function(clientId) {
   fetch()
  .then(status)
  .then(json)
  .then(function(data) {
      // TO BE DETERMINED, NOT SURE
      // WHAT TO PUT HERE

  }).catch(function(error) {
    console.log('Request failed', error);
  });
};

var getItems = function() {
   fetch()
  .then(status)
  .then(json)
  .then(function(data) {
      // TO BE DETERMINED, NOT SURE
      // WHAT TO PUT HERE
  }).catch(function(error) {
    console.log('Request failed', error);
  });
};



function status(response) {
  if (response.status >= 200 && response.status < 300) {
    return Promise.resolve(response)
  } else {
    return Promise.reject(new Error(response.statusText))
  }
}

function json(response) {
  return response.json()
}

接下来做什么?

好的,我已经建立了框架。但是,我不知道继续。我已经关注了几十个关于 Fetch 和 Promises 的教程,但它们并不完全符合我的需求,因此,我仍然卡住了。

正确的轨道上?

所以我现在担心我让这件事变得比需要的更难。通过使用承诺,我是否走上了正确的道路?

谢谢你的关注。非常感谢您的建议/代码帮助。

约翰

标签: javascriptasynchronous

解决方案


他们也不为我工作!

你好!我相信我最近遇到了和你一样的问题:“Chaining Promises”

快速搜索将我带到这里,我能够解决我的问题。

基础是,你需要从一个 Promise 中返回一个值.then()

所以在fetch()尝试这样的事情的情况下

var getQuote = function() {
  fetch(apiQuoteUrl + "GL555")
    .then(status => return status.json())
    .then(data => {
      alert(data[0].client_id);
      gClient_id = data[0].client_id;
    }).catch(error => {
      console.log('Request failed', error);
    });
};

推荐阅读