javascript - 如何链接我的承诺 - 获取不返回所需的结果
问题描述
Fetch Promise 对我不起作用
在使用 Javascript Promises 方面,我是一个新手。在我目前的项目中,我相信 Promises 是我想要完成的任务的候选者。该项目很简单,它是向客户提交报价(或估算)的在线表格。
我正在处理将显示已提交报价的页面 - ( view-quote.html )
这是分解的任务:
- 给定一个 quote_id(url 参数),我想查询 QUOTES 表。
- 在这些结果中是一个客户 ID。
- 最后,我想使用quote_id 查询ITEMS 表。
同步还是异步?
由于一个查询依赖于另一个查询,我想我可以使用 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 的教程,但它们并不完全符合我的需求,因此,我仍然卡住了。
正确的轨道上?
所以我现在担心我让这件事变得比需要的更难。通过使用承诺,我是否走上了正确的道路?
谢谢你的关注。非常感谢您的建议/代码帮助。
约翰
解决方案
他们也不为我工作!
你好!我相信我最近遇到了和你一样的问题:“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);
});
};
推荐阅读
- gremlin - 如何使用 Gremlin 沿路径收集所有顶点和边缘属性
- python - 如何将列表的多个版本(意味着我正在更新列表)添加到列表中,而不会使列表中的所有列表完全相同?
- android - 在 Android Studio 构建命令中使用 Android-NDK 失败
- c# - C# WPF 将 2 个不同的 GridViewColumn 设置为最大宽度
- angular - Angular 表单构建器验证对象中的至少一个属性为真
- java - Java Jsoup 下载 torrent 文件
- erlang - -include_lib 找不到我的库
- c++ - 在 C++ 中使用类的命名空间定义类的成员
- javascript - 如何设置 HTML 表格的布局,使其在通过 JS 输入值时不会改变?
- c# - SQLite.SQLite3:异常 System.DllNotFoundException