gpt4 book ai didi

javascript - 如何检查获取调用并返回相同的调用

转载 作者:行者123 更新时间:2023-11-30 20:27:32 28 4
gpt4 key购买 nike

我需要一种接受 promise 的方法,在其上调用 .then 来检查返回值,然后将这个 promise 完全按照系统其他部分的原样返回。上下文是我正在尝试从 GraseMonkey 脚本修改获取 API,以便我可以修改返回的数据。我通过在响应中调用 .json() 来检查它。但是,如果我不修改数据,我需要返回一个对象,该对象完全代表对获取 API 的原始调用,以便页面代码看不出有什么不同。但是当我尝试返回对象时,我得到一个错误,提示响应已经被消耗,现在我迷失在一堆我似乎无法解决的 promise 中(我不是 JS 本地人)

下面的代码是我已经拥有的并且它可以工作,但它并不是真正可以接受的,因为它重复了所有其他没有被破坏的请求。

function newFetch(){
if (needsToBeModified(arguments[0])) {

response = null;
return oldFetch.apply(this, arguments)
.then(r => {
response = r;
return r.json();
})
.then(
j => {
j = processJSON(j);
return new Promise((resolve, rej) => {
response.json = () => new Promise((resolve, reject) => resolve(j));
resolve(response);
});
},
(fail) => {
return oldFetch.apply(this, arguments)
//How can I avoid making this call here again?
}
);
} else {
return oldFetch.apply(this, arguments);
}
}

谁能告诉我一种查看 json 的方法,如果这会引发错误,则无需再次调用即可从 fetch 返回原始 promise?

谢谢。

最佳答案

fetch() 返回解析为 response object 的 promise .该响应对象的方法之一是 .clone()这听起来就像你想要的那样。来自 .clone() 的文档:

The clone() method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable.

clone() throws a TypeError if the response Body has already been used. In fact, the main reason clone() exists is to allow multiple uses of Body objects (when they are one-use only.)

我想你可以这样使用它:

function newFetch(){
let p = oldFetch.apply(this, arguments);
if (needsToBeModified(arguments[0])) {
let origResponse, cloneResponse;
return p.then(r => {
origResponse = r;
cloneResponse = r.clone();
return r.json();
}).then(j => {
j = processJSON(j);
// monkey patch .json() so it is a function that resolves to our modified JSON
origResponse.json = () => Promise.resolve(j);
return origResponse;
}, fail => {
// return clone of original response
if (cloneResponse) {
return cloneResponse;
} else {
// promise was rejected earlier, don't have a clone
// need to just propagate that rejection
throw fail;
}
});
} else {
return p;
}
}

关于javascript - 如何检查获取调用并返回相同的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50728411/

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