20211014 - Promise 解决xml2js的返回值问题
2021-10-14 00:00:00

因为Podcast的description只能在feedUrl里找到,无法直接获取,而feedUrl是xml文件,所以获取之后要先转成json格式。parseString import自xml2js的built-in方法。

修改前:直接接收parseString的返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const desc = parseString(data, (err, result) => {
if (err) {
return
}

// console.log(result)

// const { rss } = result
// const { channel } = rss
// const { description } = channel[0]
const { description } = result.rss.channel[0]
// console.log(channel)
console.log(description) // 正常值

return description
})

输出的结果是一个正常值,但返回到json中却是一个又臭又长的对象。。。

修改后:创建一个Promise,Promise里面有一个函数(executor, which is called automatically),这个executor的参数resolve和reject是两个回调函数(由js本身提供)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const desc = await new Promise((resolve, reject) => parseString(data, (err, result) => {
if (err) {
reject(null)
} else {
// console.log(result)

// const { rss } = result
// const { channel } = rss
// const { description } = channel[0]
const { description } = result.rss.channel[0]
// console.log(channel)
console.log(description)

resolve(description)
}
})).catch(error => {
console.log(error)
}) // 记得处理reject的情况!!!否则会报错!暂时的结论:await只有当resolved后才会返回given的result,如果是rejected的情况,会抛出错误,需要catch处理。

成功!

Untitled

重点:

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 result value.
  • 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" when resolve is called or "rejected" when reject is called.
  • result — initially undefined, then changes to value when resolve(value) called or error when reject(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.

参考:

How to get xml2js results out of the parser in ES6?

Promise - JavaScript | MDN

await - JavaScript | MDN

Promise