![](/img/trans.png)
[英]Promise returns an object instead of the actual string value [Javascript w/ Firebase]
[英]Returning [object Promise] instead of actual value
我是 Promise 的新手,因为我试图让一些对象在网页上显示实际值。 相反,我只是得到一堆[object Promise]
而不是
这是我到目前为止的代码:
\\ This section fetches the api results and puts them into a list/array
async function getitglinkquery(){
var linkresults = await parseitgsearchquery();
console.log(linkresults);
// var linkresultvalues = [];
for (let i = 0; i < linkresults.length; i++) {
var linkresultvalues = fetch(linkresults[i], {
method: "GET",
withCredentials: true,
headers: {
// needed to base64 encode my key with ":x" at the end of the api key then I used that for the authorization header.
"x-api-key": "INSERTAPITHINGYHERE"}})
.then(response => response.json())
}
return linkresultvalues;
}
\\**This section is trying to get the promise and parse the results**
async function parseitglinkquery() {
var queriedresults = await getitglinkquery();
console.log(typeof queriedresults);
// linkresultvalues.push(response);
const output = document.querySelector('span.ms-font-mitglue');
let pre = document.createElement('p');
pre.innerHTML = queriedresults;
pre.style.cssText += 'font-size:24px;font-weight:bold;';
output.appendChild(pre);
}
parseitglinkquery();
}
我试过的
我尝试阅读 firefox promise.resolve
方法,因为这似乎是我正在寻找的: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve但是我尝试使用他们拥有的静态 promise.resolve 方法示例对我不起作用。 像这样:
\\ This section is trying to get the promise and parse the results
async function parseitglinkquery() {
var queriedresults = await Promise.resolve(getitglinkquery());
console.log(queriedresults); \\ This is where my promises are coming out of
}
所以我认为这不是我要找的。 我也尝试在这里阅读: https : //stackoverflow.com/a/64165144但我不知道如何使用.then
方法从结果中获取变量。 我已经将.then
放在第一个函数的 api 请求中,但我仍然有一个承诺列表。
代码图片:在此处输入图片说明
结果图片:在此输入图片描述
我试过Promise.all()
但它出错了并且没有用,所以我认为这不是问题所在。 我通过使用 console.log(typeof queriedresults) 仔细检查了我的queriedresults
变量以确保它是一个对象,它说它是一个对象。
尝试的代码:
async function parseitglinkquery() {
var queriedresults = await Promise.all(getitglinkquery());
}
错误:未捕获(承诺)类型错误:对象不可迭代(无法读取属性 Symbol(Symbol.iterator))
再次失败的图片
我尝试使用:
queriedresults.then(function(result){
console.log(result)
})
基于此处的信息: https : //stackoverflow.com/a/29516570/16660683但这也不起作用,因为我收到错误消息:
Uncaught (in promise) TypeError: queriedresults.then is not a function
Promise.all
的正确用法是
async function getItglinkQuery() {
const linkresultUrls = await parseItgsearchQuery();
const linkresultPromises = [];
for (let i = 0; i < linkresults.length; i++) {
const promise = fetch(linkresults[i], {
method: "GET",
withCredentials: true,
headers: {
"x-api-key": "INSERTAPITHINGYHERE"
}
})
.then(response => response.json());
linkresultPromises.push(promise);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
return Promise.all(linkresultPromises);
// ^^^^^^^^^^^
}
现在, getItglinkQuery
返回一个值数组的承诺,而不是一个承诺数组的承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.