无法访问异步函数的响应
Can't access an async function's response
我似乎找不到从异步值访问值的方法,因为它总是 return未定义,我想等待函数结束然后检索值,但它是不工作...
async UploadFile(file): Promise<any> {
let ipfsId: any
const fileStream = fileReaderPullStream(file)
await this.ipfs.add(fileStream, { progress: (prog) => console.log(`received: ${prog}`) })
.then((response) => {
ipfsId = response[0].hash
console.log(ipfsId)
return ipfsId
//window.open("localhost:8080/ipfs/" + ipfsId);
//window.open("https://ipfs.io/ipfs/" + ipfsId);
}).catch((err) => {
console.error(err)
})
}
这是我的电话:
uploadFile(event) {
const fileSelected: File = event.target.files[0];
(async() => {
this.temp_ipfs_hash = await this.IPFS.UploadFile(fileSelected)
.then((response) => console.log(response))
console.log(this.temp_ipfs_hash)
})()
}
我想访问 return 值,但它总是 return 给我未定义或错误值...
有人知道我可以在这里尝试什么吗?
非常感谢您抽出宝贵时间! :)
编辑:我不知道 post 图片是错误的,很抱歉,我已经更改了!对不起! :(
UploadFile 应该 return 一个承诺,目前 return 什么都没有。
为了链接承诺,您应该将最后一行替换为
return this.ifps.add(...).then(...).catch(...);
使用 await 的替代方法:return await 是 promisereturned 的结果值
return await this.ifps.add(...).then(...).catch(...);
在调用者中,您可以像没有承诺一样记录结果:
console.log(this.UploadFile(fileSelected));
您同时使用了基于 promise 的 then 和 async await,您的上传文件功能应该 return 一个 promise,然后 resolve 适当地拒绝它,或者如果您想坚持使用 async-await 机制,那么您的上传文件功能将不得不改变。这是应该如何使用 async await ,假设 foobar 是一个异步函数,就像你的 ipfs.add
async function foo() {
let results = await foobar();
return results;
}
下面是如何调用这样的 foo
async function bar() {
let fooResults = await foo();
console.log(fooResults);
}
我似乎找不到从异步值访问值的方法,因为它总是 return未定义,我想等待函数结束然后检索值,但它是不工作...
async UploadFile(file): Promise<any> {
let ipfsId: any
const fileStream = fileReaderPullStream(file)
await this.ipfs.add(fileStream, { progress: (prog) => console.log(`received: ${prog}`) })
.then((response) => {
ipfsId = response[0].hash
console.log(ipfsId)
return ipfsId
//window.open("localhost:8080/ipfs/" + ipfsId);
//window.open("https://ipfs.io/ipfs/" + ipfsId);
}).catch((err) => {
console.error(err)
})
}
这是我的电话:
uploadFile(event) {
const fileSelected: File = event.target.files[0];
(async() => {
this.temp_ipfs_hash = await this.IPFS.UploadFile(fileSelected)
.then((response) => console.log(response))
console.log(this.temp_ipfs_hash)
})()
}
我想访问 return 值,但它总是 return 给我未定义或错误值... 有人知道我可以在这里尝试什么吗?
非常感谢您抽出宝贵时间! :)
编辑:我不知道 post 图片是错误的,很抱歉,我已经更改了!对不起! :(
UploadFile 应该 return 一个承诺,目前 return 什么都没有。 为了链接承诺,您应该将最后一行替换为
return this.ifps.add(...).then(...).catch(...);
使用 await 的替代方法:return await 是 promisereturned 的结果值
return await this.ifps.add(...).then(...).catch(...);
在调用者中,您可以像没有承诺一样记录结果:
console.log(this.UploadFile(fileSelected));
您同时使用了基于 promise 的 then 和 async await,您的上传文件功能应该 return 一个 promise,然后 resolve 适当地拒绝它,或者如果您想坚持使用 async-await 机制,那么您的上传文件功能将不得不改变。这是应该如何使用 async await ,假设 foobar 是一个异步函数,就像你的 ipfs.add
async function foo() {
let results = await foobar();
return results;
}
下面是如何调用这样的 foo
async function bar() {
let fooResults = await foo();
console.log(fooResults);
}