gpt4 book ai didi

javascript - 如何链接我的 promise - 获取未返回所需结果

转载 作者:行者123 更新时间:2023-12-02 22:13:04 24 4
gpt4 key购买 nike

获取 promise 对我不起作用

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

我正在处理的页面将显示已提交的报价 - (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 的教程,但它们不太符合我的需求,因此,我仍然陷入困境。

正确的轨道?

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

感谢您的浏览。非常感谢您的建议/代码帮助。

约翰

最佳答案

They weren't working for me either!

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

快速搜索给我带来了here ,我能够解决我的问题。

基础知识是,您需要从 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);
});
};

关于javascript - 如何链接我的 promise - 获取未返回所需结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59495592/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com