因为Podcast的description只能在feedUrl里找到,无法直接获取,而feedUrl是xml文件,所以获取之后要先转成json格式。parseString import自xml2js的built-in方法。
修改前:直接接收parseString的返回值
1 | const desc = parseString(data, (err, result) => { |
输出的结果是一个正常值,但返回到json中却是一个又臭又长的对象。。。
修改后:创建一个Promise,Promise里面有一个函数(executor, which is called automatically),这个executor的参数resolve和reject是两个回调函数(由js本身提供)
1 | const desc = await new Promise((resolve, reject) => parseString(data, (err, result) => { |
成功!
重点:
When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of these callbacks:
resolve(value)
— if the job is finished successfully, with resultvalue
.reject(error)
— if an error has occurred,error
is the error object.
The promise
object returned by the new Promise
constructor has these internal properties:
state
— initially"pending"
, then changes to either"fulfilled"
whenresolve
is called or"rejected"
whenreject
is called.result
— initiallyundefined
, then changes tovalue
whenresolve(value)
called orerror
whenreject(error)
is called.
💡 There can be only a single result or an error
The properties state
and result
of the Promise object are internal. We can’t directly access them. We can use the methods .then
/.catch
/.finally
for that.
await will wait for a Promise value to resolve, otherwise it’ll just wrap the value it is given in a promise and resolve the promise right away.